package cn.edu.baiyunu.myapplication.ui.utils

import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * 将时间戳格式化为易读的日期时间字符串
 */
fun formatDateTime(timestamp: Long): String {
    val date = Date(timestamp)
    val today = Calendar.getInstance()
    val dateCalendar = Calendar.getInstance().apply { time = date }
    
    return when {
        // 今天
        isSameDay(today, dateCalendar) -> {
            SimpleDateFormat("今天 HH:mm", Locale.getDefault()).format(date)
        }
        // 昨天
        isYesterday(today, dateCalendar) -> {
            SimpleDateFormat("昨天 HH:mm", Locale.getDefault()).format(date)
        }
        // 今年
        isSameYear(today, dateCalendar) -> {
            SimpleDateFormat("MM月dd日", Locale.getDefault()).format(date)
        }
        // 其他年份
        else -> {
            SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault()).format(date)
        }
    }
}

/**
 * 将时间戳格式化为yyyy-MM的字符串
 */
fun formatYearMonth(timestamp: Long): String {
    val date = Date(timestamp)
    return SimpleDateFormat("yyyy-MM", Locale.getDefault()).format(date)
}

/**
 * 判断两个日历是否为同一天
 */
private fun isSameDay(cal1: Calendar, cal2: Calendar): Boolean {
    return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
            cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)
}

/**
 * 判断cal2是否为cal1的前一天
 */
private fun isYesterday(cal1: Calendar, cal2: Calendar): Boolean {
    val yesterday = cal1.clone() as Calendar
    yesterday.add(Calendar.DAY_OF_YEAR, -1)
    return isSameDay(yesterday, cal2)
}

/**
 * 判断两个日历是否为同一年
 */
private fun isSameYear(cal1: Calendar, cal2: Calendar): Boolean {
    return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
}

/**
 * 获取当前年月，格式为yyyy-MM
 */
fun getCurrentYearMonth(): String {
    return SimpleDateFormat("yyyy-MM", Locale.getDefault()).format(Date())
}

/**
 * 获取当前年份
 */
fun getCurrentYear(): Int {
    return Calendar.getInstance().get(Calendar.YEAR)
}

/**
 * 获取当前月份 (1-12)
 */
fun getCurrentMonth(): Int {
    return Calendar.getInstance().get(Calendar.MONTH) + 1
} 